package com.example.demo.service.impl;

import com.example.demo.model.QSupplier;
import com.example.demo.model.Supplier;
import com.example.demo.model.vo.SupplierCerteriaVo;
import com.example.demo.repository.SupplierRepository;
import com.example.demo.service.SupplierService;
import com.example.demo.util.AllRecords;
import com.example.demo.util.Result;
import com.example.demo.util.ResultVO;
import com.querydsl.core.types.dsl.Expressions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by zkq19 on 2018/7/2.
 */

@Service
public class SupplierServiceImpl implements SupplierService{
    @Autowired
    private SupplierRepository supplierRepository;
    @Override
    public Result<AllRecords<Supplier>> queryPage(SupplierCerteriaVo supplierCerteriaVo) {
        com.querydsl.core.types.dsl.BooleanExpression booleanExpression = Expressions.asBoolean(true).isTrue();

        if(!StringUtils.isEmpty(supplierCerteriaVo.getCode())){
            booleanExpression = booleanExpression.and(QSupplier.supplier.code.eq(supplierCerteriaVo.getCode()));
        }
        if(!StringUtils.isEmpty(supplierCerteriaVo.getName())){
            booleanExpression = booleanExpression.and(QSupplier.supplier.name.eq(supplierCerteriaVo.getName()));
        }


        // 查找到数据

        Page<Supplier> result = supplierRepository.findAll(booleanExpression,
                new PageRequest(supplierCerteriaVo.getPageIndex() - 1, supplierCerteriaVo.getPageSize(), new Sort(Sort.Direction.DESC, "createTime")));
        //给确实的名称或字段赋值
        List<Supplier> suppliers = result.getContent();
        AllRecords<Supplier> allRecords = new AllRecords();
        allRecords.setDataList(suppliers);
        allRecords.setPageIndex(supplierCerteriaVo.getPageIndex());
        allRecords.setPageSize(supplierCerteriaVo.getPageSize());
        allRecords.setTotalNumber(result.getTotalElements());
        allRecords.setTotalPage(result.getTotalPages());
        return ResultVO.success(allRecords);
    }
}
